<template>
  <div style="padding: 0 15px;" v-loading="loading">
    <el-collapse-transition>
      <div v-show='listWrap'>
        <el-form :inline="true" :model="search" class="search" @keyup.enter.native="reList" style="height:auto">
          <!-- {{date}} -->
          <el-form-item>
              <el-date-picker
              v-model="date"
              :clearable='false'
              type="daterange"
              range-separator="至"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']"
              @change='timeChange'
              :picker-options="pickerOptions"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-input v-model="search.stud_name" placeholder="请输入学生姓名" clearable prefix-icon="el-icon-search"
              @clear="reList" style="width:150px;padding-left:5px"></el-input>
          </el-form-item>

          <el-form-item>
            <el-select v-model="search.grade" @change="gradeChange" >
              <template  v-for="(it,index) in allGrade" >
                      <el-option :key="index" :value="it.grade_id" :label="it.grade_name">
                        {{it.grade_name}}
                    </el-option>
              </template>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="search.search_class" @change="reList" style="width: 108px;">
              <el-option
                v-for="(item,index) in getNowAllClass"
                :key="index"
                :label="item.clas_name"
                :value="item.clas_id">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item>
            <el-select v-model="search.sick_type" @change="reList" style="width: 108px;">
              <el-option
                v-for="item in allSick"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <el-select v-model="search.leave_type" @change="reList" class="autoWidth">
              <el-option
                v-for="item in allLeaveType"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
           <el-form-item>
            <el-select v-model="search.type" @change="reList" class="autoWidth">
              <el-option
                v-for="item in allReason"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        <el-form-item  v-for="(it,i) in templateInfo" :key="i">
            <div v-if='it.model_type==6' style="display:flex;">
              <el-autocomplete v-model="allTemperature[i]"
              class="temperature"
              :fetch-suggestions="querySearch"
              @change="checkedNumber($event,i)"
              @select="handleSelect($event,i)"
              placeholder="请输入体温"  :disabled='!templateForm[i].value.value' clearable  style="width:228px;padding-top: 5px;margin-left:3px" @clear='reList'>
                  <el-select  value-key='value'  slot="prepend"  v-model="templateForm[i].value" :placeholder="it.title"  @change="templateInfoChange($event,i)" class="autoWidth">
                    <el-option
                      v-for="(item) in it.option_json"
                      :key="item.value"
                      :label="item.label"
                      :value="item">
                    </el-option>
                  </el-select>
                  <template slot-scope="{ item }">
                    <div class="name">{{ item.value }}{{ item.address }}</div>
                    <!-- <span class="addr"></span> -->
                  </template>
              </el-autocomplete>

            </div>
            <el-select v-if='it.model_type!==6' value-key='value' v-model="templateForm[i].value" @change="templateInfoChange($event,i)" class="autoWidth" style="margin-left:3px">
              <el-option
                v-for="(item) in it.option_json"
                :key="item.value"
                :label="item.name"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="reset()">重置</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="downFile(1)">导出当前表</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="downFile(2)">下载图片附件</el-button>
          </el-form-item>
          <!-- <el-form-item>
            <el-button type="primary" @click="test(2)">测试</el-button>
          </el-form-item> -->
        </el-form>
        <!-- <el-table :data="tableData" style="width: 100%;" border stripe v-loading="loading">
          <el-table-column prop="template_name" label="模板名称">
          </el-table-column>
          <el-table-column label="是否开启" align="center" width="80">
            <template slot-scope="props">
              <el-switch v-model="props.row.open_btn" @change="changeSwitch($event, props.row)"
                :loading="props.row.loading" active-value="1" inactive-value="0"></el-switch>
            </template>
          </el-table-column>

          <el-table-column prop="insert_time" align="center" label="创建时间" width="200">
          </el-table-column>
          <el-table-column fixed="right" align="center" label="操作" width="210">
            <template slot-scope="props">
              <el-link type="primary" title="编辑当前模板" @click="handleEdit(props.$index, props.row)">编辑</el-link>
              <el-link type="primary" title="预览当前模板详情" :disabled="props.row.plan_status == 1"
                @click="handleView(props.$index, props.row)">预览</el-link>
              <el-popconfirm :title="'是否删除【'+props.row.template_name+'】模板?'" @confirm="handleDel(props.$index, props.row)">
                <el-link slot="reference" type="danger" title="删除当前模板">删除 </el-link>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table> -->

        <el-table  style="width: 100%" :data="tableData" border highlight-current-row stripe table-layout='auto'>
          <template v-for="(item,index) in tabledHead">
            <el-table-column
                :prop="item.key"
                :key="item.key"
                :label="item.title"
                :width="setWidth(item.key,tableData)"
                align="center"
              >
                <template slot-scope="scope">
                  <span v-if="scope.row[index][item.key].type==7 &&  scope.row[index][item.key]['value']!==''" style="display:flex">
                    <template  v-for="(it,i) in scope.row[index][item.key]['value'].split(',')" >
                      <el-image  :key="i" style="width:24px; height: 24px;cursor:zoom-in" title="放大图片"
                      :src="it"
                      :preview-src-list="scope.row[index][item.key]['value'].split(',')" class="imgList">
                    </el-image>
                   </template>
                  </span>
                  <span v-else >
                      {{scope.row[index][item.key]['value']}}
                  </span>
                  <!-- <img v-else :width="44" :height="44" :src="scope.row[index][item.key]"/>
                  <sc-upload v-model="scope.row[index][item.key]" title="上传头像"></sc-upload> -->
                </template>
              </el-table-column>
            </template>
       </el-table>

        <!-- 分页 -->
        <el-pagination :currentPage=search.pageNo :page-size=search.pageSize :page-sizes="[10, 40, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper" :total="allTotal" @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </el-collapse-transition>
    <!-- :hide-on-single-page="allTotal<20" -->
    <!-- 预览模板 -->
    <el-dialog title="预览模板" :visible.sync="dialogInfoVisible" width="794">
      <div class="checkSendObj">
        <div class="formView">
          <el-divider content-position="center">回执单</el-divider>
          <ul>
            <li v-for="(item, index) in nowView" v-bind:key="index">
              <div style="display: flex;">
                <!-- <div>{{ index + 1 }}. {{ item.label }}:</div> -->
                <div style="padding-right: 10px;">{{ item.label }} :</div>
                <div v-if="item.type == 'input'" class="inputType" :style="{ width: (item.maxlength * 15) + 'px' }"></div>
                <div v-else>
                  <span v-for="(it, i) in item.option" v-bind:key="i" :class="[{ 'checked': false}, 'optionShow']">
                    <!-- <span style="font-size: 22px;">□ </span> -->
                    <span>{{ it.name }}</span>
                  </span>
                </div>
              </div>
            </li>
          </ul>
          <div class="sealWrap">
            <div style="padding-top: 35px;">家长签字：</div>
            <div class='schoolInfo'>
              <div>
                <div>{{ org_name }}</div>
                <div>{{ time }}</div>
              </div>
              <img v-if='sealShow' :src="image" alt="" class="el-upload-list__item-thumbnail schoolImg">
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
export default {
  name: 'List',
  data () {
    return {
      tableData: [],
      // 班级详情搜索
      loading: false,
      listWrap: true,
      // 总条数
      allTotal: 0,
      // 所有的体温
      allTemperature: {'0': '1', '1': '1', '2': '1', '3': '1'},
      // 0：普通病 ；1：传染病； 2：意外伤害；
      allSick: [{
          value: '',
          label: '病假类型'
        }, {
          value: '0',
          label: '普通病'
        }, {
          value: '1',
          label: '传染病'
        }, {
          value: '2',
          label: '意外伤害'
        } ],
        allLeaveType: [{
          value: '',
          label: '请假类型'
        }, {
          value: '0',
          label: '全天假'
        }, {
          value: '1',
          label: '小时假'
        }],
        allReason: [{
          value: '',
          label: '请假原因'
        }, {
          value: '0',
          label: '病假'
        }, {
          value: '1',
          label: '事假'
        }],
      search: {
        'begin_date': '2023-01-01',
        'end_date': '2023-12-31',
        'search_class': '',
        'stud_name': '',
        'grade': '',
        'leave_type': '',
        'type': '',
        'sick_type': '',
        'query_params': '', // JSON.stringify([{'model_id': 10, 'value': '十全十美'}])
        'pageNo': 1,
        'date': [],
        'pageSize': 10,
        'nowTemperature': '', // 当前体温
        'operator': ''
      },
      date: [],
      nowView: '',
      org_name: '',
      image: '',
      sealShow: true,
       time: '',
      dialogInfoVisible: false, // 编辑模板窗口

      tabledHead: [],
      // 所有班级数组
      allGrade: [],
      // 所有年级班级Obj
      allClass: {},
      getNowAllClass: [],
      // 模板筛选项
      templateInfo: [],
      templateForm: {},
      // 体温符号
      allOperator: [{
          value: '',
          label: '当前体温'
        }, {
          value: '1',
          label: '>'
        }, {
          value: '2',
          label: '≥'
        }, {
          value: '3',
          label: '='
        }, {
          value: '4',
          label: '<'
        }, {
          value: '5',
          label: '≤'
        }],
        restaurants: [],
        flagTime: '',
        pickerOptions: {
          // 最长选择2个月
          onPick: ({maxDate, minDate}) => {
              this.flagTime= minDate.getTime()
              if (maxDate) {
                this.flagTime= ''
              }
            },
          disabledDate: (time) => {
              if (this.flagTime!== '') {
                const one = 30 * 24 * 3600 * 1000 * 2
                const minTime = this.flagTime- one
                const maxTime = this.flagTime+ one
                return time.getTime() < minTime || time.getTime() > maxTime
              }
            }
        }
    }
  },
  mounted() {
      this.restaurants = this.loadAll()
  },
  watch: {
  },
  created () {
    let _this = this
    this.detailData = []

    // 设置默认查询日期：获取当前日期
    // 结束
    var today = new Date()
    var year = today.getFullYear()// 获取年份
    var month = today.getMonth() + 1// 获取月份
    var day = today.getDate()// 获取日期
    // 一个月前
    var yesterday = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000)
    console.log(yesterday.getFullYear() + '-' + (yesterday.getMonth() + 1) + '-' + yesterday.getDate())
    console.log(year + '-' + month + '-' + day)
    this.search.begin_date = yesterday.getFullYear() + '-' + (yesterday.getMonth() + 1) + '-' + yesterday.getDate()
    this.search.end_date = year + '-' + month + '-' + day
    this.date = [this.search.begin_date + ' 00:00:00', this.search.end_date + ' 23:59:59']

    // 获取模板信息
    this.getTemplateInfo()
    // 判断权限
    let rlids = sessionStorage.getItem('rlids')
    let mapNJ = JSON.parse(sessionStorage.getItem('mapNJ'))

    let purview = null
    if (typeof rlids !== 'object' && rlids !== null) {
         purview = rlids.substring(0, rlids.length - 1).split(',')
    } else {
         purview = rlids
    }

    // 管理员、校长、分校校长、考勤管理员能够查看全校所有年级班级下的学生考勤；年级组长能够查看年级下的学生考勤；班主任、普通任课教师能查看授课班级的学生考勤。
    if (purview.indexOf('19') < 0 && purview.indexOf('2') < 0 && purview.indexOf('1') < 0 && purview.indexOf('10') < 0 && purview.indexOf('3') < 0 && purview.indexOf('4') < 0 && purview.indexOf('5') < 0) {
        this.$alert('您没有考勤请假的访问权限！', {
          confirmButtonText: '确定',
          callback: action => {
            window.location.href = '#4'
          }
        })
    }
    // 考勤管理员，管理员、校长、分校校长、考勤管理员--显示当日考勤，考勤管理
    if (purview.indexOf('19') < 0 && purview.indexOf('1') < 0 && purview.indexOf('2') < 0 && purview.indexOf('10') < 0 && purview.indexOf('5') < 0) {
          // 班主任、任课
          this.dealLocalData(function() {
            _this.list()
          })
    } else if (purview.indexOf('5') >= 0 && purview.indexOf('19') < 0 && purview.indexOf('1') < 0 && purview.indexOf('2') < 0 && purview.indexOf('10') < 0) {
         // 处理一个年级
         // let dealData = []
         let gradeIds = []
          // 年级管理员
          for (var i = mapNJ.length - 1; i >= 0; i--) {
              // 显示字段obj.grade_number取余8，9，0的（新生年级）不显示 2019/12/30/09:57 孙伟 海洋
              var showTip = Number(mapNJ[i].grade_number) % 10
              if (showTip === 8 || showTip === 9 || showTip === 0) {
                  continue
              }
              gradeIds.push(mapNJ[i].grade_id)
          }
          // this.allGrade = dealData
          this.getGradeClass(gradeIds)

          var promise = new Promise((resolve, reject) => {
            this.getGradeClass(gradeIds, function() {
              resolve(1)
            })
          })
          promise.then((data) => {
            _this.list()
          })
      // 处理班主任和任课
      // this.dealLocalData()
    } else {
         // 获取年级班级
          this.getAllClass(function() {
             _this.list()
          })
    }
  },
  computed: {
  },
  methods: {
    // 只能输入小数和整数35-42
    checkedNumber(value, obj) {
      const oldValue=value
      value = value.replace(/[^\d|.]/g, '')
      let dealValue = value < 35 || value > 42.9 ? '' : value
      this.allTemperature[obj] = dealValue
      if (value === ''&&oldValue!=='') {
        // this.$message('只能输入35-42的数字', '提示', { type: 'warning' })
        this.$message({
          message: '只能输入35-42.9的数字',
          type: 'warning'
        })
      } else {
        this.list()
      }
    },
    // 提问输入自动完成
    querySearch(queryString, cb) {
        var restaurants = this.restaurants
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
        // 调用 callback 返回建议列表的数据
        cb(results)
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
        }
      },
      loadAll() {
        let allTemperatureArray = []
        let InitialNumber = 35
        for (let a = 350, b = 430; a < b; a++) {
          allTemperatureArray.push({ 'value': InitialNumber.toFixed(1), 'address': '℃' })
          InitialNumber += 0.1
        }
        return allTemperatureArray
      },
      handleSelect(item, i) {
        console.log(item)
        this.allTemperature[i] = item.value
        this.list()
      },
    // test(value, i) {
    //   this.allTemperature[i || 1].value = 36
    //   this.$forceUpdate()
    // },
       // 自适应表格列宽
      setWidth(str, tableData) {
      // str为该列的字段名(传字符串);tableData为该表格的数据源(传变量);
      str = str + ''
      let columnContent = ''
      let maxObj = null
      if (!tableData || !tableData.length || tableData.length === 0 || tableData === undefined) {
        return
      }
      if (!str || !str.length || str.length === 0 || str === undefined) {
        return
      }

       let nowL = str.replace('key', '')
        // 获取该列中最长的数据(内容)
        let index = 0
        for (let i = 0; i < tableData.length; i++) {
          if (tableData[i][nowL][str] === null) {
            return
          }

          const nowTemp = tableData[i][nowL][str].value || tableData[i][nowL][str].title + ''
          const maxTemp = (maxObj ? maxObj.value:'') || tableData[index][nowL][str].value || tableData[index][nowL][str].title + ''

          if (nowTemp.length > maxTemp.length) {
            // index = i
            maxObj = tableData[i][nowL][str]
          } else {
            maxObj = maxObj ||tableData[index][nowL][str] || tableData[index][nowL][str]
          }
        }
      console.log(maxObj.value)
      if (maxObj.type === 7) {
        for (let a = 0, b = maxObj.value.split(',').length; a < b; a++) {
          columnContent += '刘9'
        }
      } else {
        columnContent = maxObj.value || maxObj.title + ''
      }
      // 以下分配的单位长度可根据实际需求进行调整
      let flexWidth = 0
      for (const char of columnContent) {
        if ((char >= 'A' && char <= 'Z') || (char >= 'a' && char <= 'z')) {
          // 如果是英文字符，为字符分配8个单位宽度
          flexWidth += 12
        } else if (char >= '\u4e00' && char <= '\u9fa5') {
          // 如果是中文字符，为字符分配15个单位宽度
          flexWidth += 18
        } else {
          // 其他种类字符，为字符分配8个单位宽度
          flexWidth += 9
        }
      }
      if (flexWidth < 100) {
        // 设置最小宽度
        flexWidth = 100
      }
      return flexWidth + 'px'
    },
    timeChange(e, b) {
      if (typeof e !== 'object') {
         this.data = [e, e]
      }
      this.search.pageNo=1
      this.list()
    },
    templateInfoChange(e, b) {
      if (e.value === '' && e.type === 6) {
        this.allTemperature[b] = ''
      }
      this.templateForm[b].value = e
      this.templateForm = Object.assign({}, this.templateForm)
      this.search.pageNo=1
      this.list()
    },
    // 本地数据生成班主任任课
    dealLocalData(okFun) {
      let mapRK = JSON.parse(sessionStorage.getItem('mapRK'))
      let mapBZR = JSON.parse(sessionStorage.getItem('mapBZR'))
      let allData = mapBZR.concat(mapRK)

      let allGClassId = []
      let gradeIndex = 0
      // 生成年级班级信息
      for (var i = allData.length - 1; i >= 0; i--) {
          var obj = allData[i]
          var gradeId = obj.grade_id
          // 年级信息
          let gradeObj = {
              grade_id: obj.grade_id,
              grade_name: obj.grade_name,
              grade_number: obj.grade_number,
              clasList: []
            }
          // 班级信息
          let classObj = {
                    clas_id: obj.clas_id,
                    clas_name: obj.clas_name
                  }

          let allClassId = []
          // let allClass = []
          if (!allGClassId.includes(obj.clas_id)) {
            allGClassId.push(obj.clas_id)
          }
          // 判断年级是否存在
          if (this.allClass[gradeId] === undefined) {
              this.allClass[gradeId] = gradeIndex
              gradeObj.clasList.push(classObj)
              allClassId.push(obj.clas_id)
              this.allGrade.push(gradeObj)
              gradeIndex += 1
          } else {
              // 查询该年级下是否已包含本班级
              let targetGrade = this.allGrade[this.allClass[gradeId]]
              let isHas = false
              for (var a = 0, b = targetGrade.clasList.length; a < b; a++) {
                 let objId = targetGrade.clasList[a].clas_id
                 if (objId === classObj.clas_id) {
                  isHas = true
                  break
                 }
              }
              if (!isHas) {
                // 判断班级是否重复
                allClassId.push(obj.clas_id)
                targetGrade.clasList.push(classObj)
              }
          }
      };
      // 生成班级年级关联
      this.allGrade.map(item => {
        let allClassId = []
        item.clasList.map(item => {
          allClassId.push(item.clas_id)
        })

        item.clasList.unshift({
          clas_id: allClassId.join('_'),
          clas_name: '全部班级'
        })

        this.allClass[item.grade_id] = item.clasList
      })

      this.allGrade.unshift({
          grade_id: 1000000,
          grade_number: 0,
          grade_name: '全部年级',
          clasList: [{
            clas_id: allGClassId.join('_'),
            clas_name: '全部班级'
          }]
        })
        this.allClass[1000000] = [{
            clas_id: allGClassId.join('_'),
            clas_name: '全部班级'
          }]
      // 年级排序
      this.allGrade.sort(function(a, b) {
          if (a.grade_number < b.grade_number) {
              return -1
          }
          if (a.grade_number > b.grade_number) {
            return 1
          }
          return 0
      })

      // 设置默认值
      this.search.grade = 1000000
      this.getNowAllClass = this.allClass[1000000]
      this.search.search_class = this.allClass[1000000][0].clas_id

      console.log(this.allGrade)
      if (okFun) { okFun() }
    },
    // 获取模板列表
    async getTemplateInfo() {
            this.loading = true
            const res = await this.$api.plan.templateList.get({})
            if (res.code === 200) {
                let allDealData = []
                let lNumber = 0
                res.data.map((item, index) => {
                    let mType = item.model_type
                    if ((mType === 6 || mType === 8) && item.is_fixed === 0) {
                        item.option_json = item.option_json === '' ? [] : JSON.parse(item.option_json)

                        item.option_json.unshift({
                          name: item.title,
                          id: item.id,
                          type: item.model_type,
                          value: ''
                        })
                        if (mType === 8) {
                          this.templateForm[lNumber] = {
                            name: item.title,
                            value: item.option_json[0]
                          }
                        }
                        if (mType === 6) {
                          item.option_json = JSON.parse(JSON.stringify(this.allOperator))
                          item.option_json[0]['label'] = item.title
                          this.templateForm[lNumber] = {value: this.allOperator[0]}
                          this.allTemperature[lNumber] = ''
                        }
                        item.option_json.map(it => {
                          it.id = item.id
                          it.type = item.model_type
                        })

                        allDealData.push(item)
                        lNumber++
                    }
                })
                this.templateInfo = allDealData
                this.loading = false
                console.log(this.templateInfo)
                // console.log(this.templateForm)

                // id和位置简历对应
            } else {
                this.loading = false
                this.$alert(res.message, '提示', { type: 'error', closeOnHashChange: !1 })
            }
        },
    // 重置搜索条件
    reList () {
      this.search.pageNo = 1
      this.list()
    },
    searchParameter() {
        // 生成模板查询条件
      let searchTList = []
      // this.templateForm.map(it => {
      for (let it in this.templateForm) {
        if (this.templateForm[it].value !== '') {
          let changedObj = this.templateForm[it].value
          let changedValue = changedObj.value
          if (changedObj.type === 6) {
            changedValue = changedObj.value + '_' + this.allTemperature[it]
            if (this.allTemperature[it] !== '' && changedObj.value !== '') {
              searchTList.push({
                'model_id': changedObj.id,
                'value': changedValue,
                'type': changedObj.type
              })
            }
          } else {
            if (changedObj.value !== '') {
              searchTList.push({
              'model_id': changedObj.id,
              'value': changedObj.name,
              'type': changedObj.type
            })
            }
          }
        }
      }

      this.search.query_params = JSON.stringify(searchTList)
      this.search.begin_date = this.date[0]
      this.search.end_date = this.date[1]
      return this.search
    },
    // 获取模板列表
    async list () {
      this.loading = true
      const res = await this.$api.plan.list.get(this.searchParameter())
      if (res.code === 200) {
        this.tabledHead = []
        // 生成表头
        res.data.head_list.map((item, index) => {
            this.tabledHead.push({'key': 'key' + index, 'title': item})
        })

        let allDealData = []
        res.data.page.data.map((item) => {
          let dealData = []
          item.map((it, index) => {
            let obj = ''
            obj = {['key' + index]: it}
            dealData.push(obj)
          })
          allDealData.push(dealData)
        })
        this.tableData = allDealData
        this.loading = false
        // 分页
        this.allTotal = res.data.page.total
      } else {
        this.loading = false
        this.$alert(res.message, '提示', { type: 'error', closeOnHashChange: !1 })
      }
    },
    async getAllClass (okFun) {
      this.loading = true
      const res = await this.$api.plan.getAllClass.get(this.search)
      if (res.code === 200) {
        let dealData = []
        let dealAllClass = []
        let allGClassId = []
        res.data.depData.map(item => {
          if (item % 10 !== 0 && item.clasList.length !== 0) {
           let allClassId = []
           let allClass = []
           item.clasList.map(item => {
              let obj = {
                    clas_id: item.clas_id,
                    clas_name: item.clas_name
                  }
                  allClassId.push(item.clas_id)
                  allClass.push(obj)
                  allGClassId.push(item.clas_id)
           })
           item.clasList = allClass
           item.clasList.unshift({
                    clas_id: allClassId.join('_'),
                    clas_name: '全部班级'
                  })
            dealAllClass[item.grade_id] = item.clasList
            dealData.push(item)
          }
        })

        this.allGrade = dealData
        this.allGrade.unshift({
          grade_id: 1000000,
          grade_name: '全部年级',
          clasList: [{
            clas_id: allGClassId.join('_'),
            clas_name: '全部班级'
          }]
        })
        dealAllClass[1000000] = [{
            clas_id: allGClassId.join('_'),
            clas_name: '全部班级'
          }]
        this.allClass = dealAllClass
        this.search.grade = 1000000
        console.log(dealData)
        this.search.search_class = allGClassId.join('_')
        this.getNowAllClass = [{
            clas_id: allGClassId.join('_'),
            clas_name: '全部班级'
          }]
        // console.log(dealData)
        if (okFun) { okFun() }
      } else {
        this.loading = false
        this.$alert(res.message, '提示', { type: 'error', closeOnHashChange: !1 })
      }
    },
    async getGradeClass (gradeIds, okFun) {
      this.loading = true
      const res = await this.$api.plan.getAllClass.get({})
      if (res.code === 200) {
        let dealData = []
        let dealAllClass = []
        let allGClassId = []
        res.data.depData.map(item => {
          if (item % 10 !== 0 && item.clasList.length !== 0) {
            // 只有自己管理理论的年级才显示
            if (gradeIds.includes(item.grade_id)) {
                let allClassId = []
                let allClass = []
                item.clasList.map(item => {
                    let obj = {
                          clas_id: item.clas_id,
                          clas_name: item.clas_name
                        }
                        allClassId.push(item.clas_id)
                        allClass.push(obj)
                        allGClassId.push(item.clas_id)
                })

                item.clasList = allClass
                item.clasList.unshift({
                          clas_id: allClassId.join('_'),
                          clas_name: '全部班级'
                        })
                  dealAllClass[item.grade_id] = item.clasList
                  dealData.push(item)
            }
          }
        })

        this.allGrade = dealData
        this.allGrade.unshift({
          grade_id: 1000000,
          grade_name: '全部年级',
          clasList: [{
            clas_id: allGClassId.join('_'),
            clas_name: '全部班级'
          }]
        })
        dealAllClass[1000000] = [{
            clas_id: allGClassId.join('_'),
            clas_name: '全部班级'
          }]
        this.allClass = dealAllClass
        this.search.grade = 1000000
        this.search.search_class = allGClassId.join('_')
        this.getNowAllClass = [{
            clas_id: allGClassId.join('_'),
            clas_name: '全部班级'
          }]
          if (okFun) { okFun() }
      } else {
        this.loading = false
        this.$alert(res.message, '提示', { type: 'error', closeOnHashChange: !1 })
      }
    },
    gradeChange(val) {
      this.getNowAllClass = this.allClass[val]
      this.search.search_class = this.allClass[val][0].clas_id
      this.search.pageNo = 1
      this.list()
    },
    // // 表格内开关事件
    // async changeSwitch (val, row) {
    //   // 1.还原数据
    //   row.open_btn = row.open_btn === '1' ? '0' : '1'
    //   // 2.执行加载
    //   row.loading = true
    //   const res = await this.$api.plan.switch.post({ id: row.id, open_btn: val })
    //   if (res.code === 200) {
    //     delete row.loading
    //     row.open_btn = val
    //     // this.$refs.table.refresh()
    //     this.$message.success(`操作成功:模板【${row.template_name} 】已${Number(val) === 0 ? '关闭' : '开启'}`)
    //   } else {
    //     row.is_using = val === '1' ? '0' : '1'
    //     this.$alert(res.message, '提示', { type: 'error' })
    //   }
    // },
    // 分页操作-修改显示页数-每页显示指定条数
    handleSizeChange (e) {
      this.search.pageNo = 1
      this.search.pageSize = e
      this.list()
    },
    // 分页操作-跳转到指定页 跳转到指定页数
    handleCurrentChange (e) {
      this.search.pageNo = e
      this.list()
    },
    // 格式化参数【下载】下载用
    parseParams (data) {
      try {
        let tempArr = []
        for (let i in data) {
          let key = encodeURIComponent(i)
          let value = encodeURIComponent(data[i])
          tempArr.push(key + '=' + value)
        }
        let urlParamsStr = tempArr.join('&')
        return urlParamsStr
      } catch (err) {
        return ''
      }
    },
    reset () {
      window.location.reload()
    },
    // 下载模板或者Excel
    async downFile (type) {
      // var str = this.nowPlan.plan_name + (type === 2 ? '详情' : '个性化收费模板') + new Date().toLocaleString().replace(/[/\s:]/g, '') + '.xlsx'
      const parameter = {
        'org_id': sessionStorage.org_id,
        'token': sessionStorage.token,
        'udid': sessionStorage.udid
        // 'fileName': str
      }
      const downParameter = Object.assign(parameter, this.searchParameter())
      // 原始写法 新的是以流的方式下载，本地生成文件
      window.location.href = (type === 1 ? this.$api.plan.downList.url : this.$api.plan.downImg.url) + '?' + this.parseParams(downParameter)
      // var url = type === 1 ? this.$api.planDetail.downTemplate.down(downParameter) : this.$api.planDetail.downExcel.down(downParameter)
      // const res = await url
    },
    // 选择excle格式判断
    getFile (event, b) {
      if (event !== '' && !event.includes('.xlsx')) {
        document.getElementById('upload-file').value = ''
        this.$alert('目前仅支持excel2007及更高版本的.xlsx格式文件！', '提示', { type: 'warning' })
        return false
      }
    },
    // 弹出窗口 日期相关操作++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    // 关闭预览窗口
    close (e, info) {
      this.dialogInfoVisible = false
    },
    // 关闭预览窗口 提示
    handleClose (done) {
      this.$confirm('确认要关闭编辑窗口吗？')
        .then(_ => {
          done()
        })
        .catch(_ => { })
    },
    // 输入校验 文档：校验文字<>& {} |*=;%  单行文本框禁止输入英文特殊字符<>&{}|*=;%
    checkText (string) {
      // const pattern = /[`~!@#$^\-&*()=|{}':;',\\\[\]\.<>\/?~！@#￥……&*（）——|{}【】'；：""'。，、？\s]/g
      const pattern = /[`<>& {} |*=;%\s]/g
      const str = string.replace(pattern, '')
      this.dialogForm.plan_name = str
    },
    // A 数组 是否包含B数组
    arrayIncludes (arr1, arr2) {
      return arr2.every(val => arr1.includes(val))
    },

    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    // 预览模板
    async handleView (e, info) {
      this.dialogInfoVisible = true
      this.sealShow = info.is_seal === 1
      this.time = info.insert_time_str

      this.org_name = info.org_name
      this.image = info.image
      this.nowView = JSON.parse(info.template_json)
    },

    // 删除模板
    async handleDel (index, info) {
      //  this.$confirm('删除模板会同时删除相关的全部数据，确认要删除吗?', '提示', {
      //    confirmButtonText: '确定',
      //    cancelButtonText: '取消',
      //    type: 'warning'
      //  }).then(async () => {
      const delPr = { ids: info.id, template_name: '' }
      const res = await this.$api.plan.del.post(delPr)
      if (res.code === 200) {
        this.list()
      } else {
        this.$alert(res.message, '提示', { type: 'error' })
      }
      //  }).catch(() => {
      //  })
    },
    handleEdit (index, obj) {
       this.$parent.$parent.editTemplate = obj
      this.$parent.$parent.activeName = 'tabs1Flag'
      this.$parent.$parent.nowName = '编辑模板'
      this.$parent.$parent.tabsArr.tabs1Flag = true
      this.$parent.$parent.tabsArr.tabs2Flag = false
      this.$parent.$parent.tabsArr.tabs3Flag = false
    },
    toFirst (isEdit, obj) {
      this.$parent.$parent.activeName = 'tabs1Flag'
      this.$parent.$parent.nowName = isEdit ? '编辑模板' : '新建模板'
      this.$parent.$parent.tabsArr.tabs1Flag = true
      this.$parent.$parent.tabsArr.tabs2Flag = false
      this.$parent.$parent.tabsArr.tabs3Flag = false
    },
    toThird () {
      this.$parent.$parent.activeName = 'tabs3Flag'
      this.$parent.$parent.nowName = '落款设置'
      this.$parent.$parent.tabsArr.tabs3Flag = true
      this.$parent.$parent.tabsArr.tabs2Flag = false
      this.$parent.$parent.tabsArr.tabs1Flag = false
    }

  }
}
</script>
<style>
#app {
  font-family: Helvetica, sans-serif;
  text-align: center;
}

.el-table td,
.el-table th {
  padding: 5px 0;
  font-size: 14px;
}

.el-table td .el-button {
  padding: 8px 0px;
}

.el-link {
  margin-right: 10px;
}

.el-table__empty-block {
  max-height: 99px;
}

.el-textarea .el-input__count {
  background: none;
  bottom: -36px;
}

.el-dialog__body {
  padding: 0 30px;
  border: 1px #fff solid;
}

.checkSendObj .el-checkbox-group {
  margin-left: 21px;
  display: flex;
}

.search {
  background: #fbfafa;
  padding: 10px 12px 12px 12px;
  min-height: 30px;
  height: 36px;
  overflow: hidden;
}

.search .el-form-item {
  margin-bottom: 0;
}

.search .el-range-editor.el-input__inner {
  padding: 0px 10px;
  margin-top: 0px;
}

.el-pagination {
  padding: 18px 0px;
}

.checkSendObj .el-form-item__content {
  padding-left: 20px;
}

.search .el-form-item__content {
  padding-left: 0;
}

.el-popover {
  max-width: 240px;
}

.el-popconfirm__main {
  padding: 5px 0;
}

body {
  overflow: auto;
  background-color: #fff;
}

.fileInput input {
  border: none;
}

/* 统计信息 */
.echarsWrap {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
  flex-direction: row;
  margin-bottom: 15px;
  position: relative;
  padding: 20px 20px 0px 20px;
}

.echarsWrap legend {
  color: #496f8f;
  font-weight: bold;
}

.echarsWrap fieldset {
  margin-left: 15px;
  background-image: -webkit-linear-gradient(330deg, #fbfdff, #e1e8ef);
  background-image: -o-linear-gradient(330deg, #fbfdff, #e1e8ef);
  background-image: linear-gradient(120deg, #fbfdff, #e1e8ef);
  background-size: cover;
  border-radius: 5px;
  overflow: hidden;
  padding: 0 40px 0px 20px;
  position: relative;
}

.oneEcharsShow .oneEcharsNum {
  font-size: 24px;
  font-family: "sans-serif";
  font-weight: bold;
  line-height: 44px;
  text-align: center;
  height: 48px;
}

.planTitleWrap .planTitle {
  font-weight: bold;
  font-size: 16px;
}

.echarsWrap .oneEcharsTitle {
  font-size: 12px;
  position: absolute;
  right: 20px;
  top: 20px;
}

.el-table .cell {
  line-height: 24px;
  transform: translate3d(0, 0, 0);
}

.el-picker-panel__footer button:first-child {
  display: none;
}

.el-table__fixed-right {
  min-height: 75px;
}
.el-image-viewer__actions,.el-image-viewer__close {
  overflow: hidden;
}
.imgList {
  display: inline-flex;
    justify-content: center;
    align-items: center;
    box-sizing: border-box;
    text-align: center;
    overflow: hidden;
}
.imgList img {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  cursor: zoom-in;
}
.el-input--suffix .el-input__inner {
  padding-right: 6px;
}
.el-date-editor--daterange.el-input__inner {
  width: 280px;
}
.el-form--inline .el-form-item {
  margin-right: 2px;
}
.el-image-viewer__next, .el-image-viewer__prev,.el-image-viewer__close{
  display: -webkit-inline-box;
  overflow: hidden;
}
.temperature .el-input--suffix .el-input__suffix {
  top: -5px;
}
.temperature .el-input--suffix  .el-input-group__prepend .el-input__suffix {
  top: 5px;
}
.el-input-group__prepend {
  background: #fff;
}

.autoWidth {
  min-width: 120px;
  text-align: start;
}
.autoWidth .el-input__prefix {
  position: relative;
  box-sizing: border-box;
  border: 1px solid #ffffff00;
  padding: 0 40px;
  height: 40px;
  line-height: 40px;
  color: #606266;
  left: 0;
  visibility: hidden;
}
/* .autoWidth .el-input__inner {
  position: absolute;
} */

</style>
